package net.dao.impl;

import net.dao.ObjetoDao;
import net.model.Objeto;

import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository(value = "objetoDao")
public class ObjetoDaoImpl implements ObjetoDao {

	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public Integer getCantidadObjetos() {
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(
				Objeto.class);
		return criteria.list().size();
	}

	@Override
	public void saveObjeto(Objeto objeto) {
		try {
			sessionFactory.getCurrentSession().saveOrUpdate(objeto);
		} catch (org.hibernate.NonUniqueObjectException e) {
			reattachToHibernateSession(objeto);
		}
	}

	public void reattachToHibernateSession(Objeto obj) {
		if (obj != null && obj.getId() != 0) {
			if (!sessionFactory.getCurrentSession().contains(obj)) {
				Object oldObj = sessionFactory.getCurrentSession().get(
						obj.getClass(), obj.getId());
				if (oldObj != null) {
					sessionFactory.getCurrentSession().evict(oldObj);
				}
				sessionFactory.getCurrentSession().lock(obj, LockMode.NONE);
			}
		}
	}

}
